<template>
  <z-paging ref="paging" v-model="dataList" @query="queryList" :auto="false">
    <!-- 导航栏 -->
    <template #top>
      <uv-navbar title="购物车" placeholder :autoBack="true" />
    </template>
    <!-- 商品列表 -->
    <u-checkbox-group v-model="checkboxValue">
      <view class="w100 p-32">
        <view v-for="(item, index) in dataList" :key="index"
          @click.stop="item.add_type == 2 ? specificas.open(item) : null">
          <view class="main-bg-color m-b-20 w100 p-x-26 p-y-30 position-relative">
            <view class="flex" style="border-radius: 12rpx;overflow: hidden;">
              <!-- 复选框 -->
              <view class="">
                <view class="flex-ali">
                  <u-checkbox :checked="item.checked" :name="item" @change="(v) => handleCheckChange(index, v)"
                    activeColor="#830102" />

                  <!-- 商品图片 -->
                  <u-image :src="item.image" width="168rpx" height="168rpx" radius="8rpx" />
                </view>
              </view>
              <!-- 商品信息 -->
              <view class="m-l-20" style="flex: 1">
                <view class="font-32 font-weight-bold">
                  {{ item.product_name }}
                </view>
                <view class="m-b-30 m-t-10 flex-wra" style="gap: 20rpx" v-if="item.add_type == 1">
                  <view v-for="(it, index) in item.suk.split(',')" :key="index">
                    <u-tag type="info" bgColor="#F3F3F3" borderColor="#F3F3F3" color="#333" size="mini">{{ it }}</u-tag>
                  </view>
                </view>
                <view class="m-b-30 m-t-10 " style="gap: 20rpx" v-else>
                  <view class="font-26 font-weight-middle"> 实际周长:{{ item.reality_size }}cm
                  </view>
                  <view class="font-26 m-t-10 font-weight-middle"> {{ item.suk.line.product_name }}({{ item.suk.line.suk
                  }}){{ item.total_number || '0' }}颗珠子
                    <!-- {{item.suk.materials.map(item2 => item2.product_name + 'x' + item2.number).join('、')}} -->
                  </view>
                </view>

                <view class="flex-ali-bet m-t-30" v-if="item.add_type == 1">
                  <view class="text-main font-36 font-weight-bold">￥{{ item.price / 100 }}</view>
                  <!-- 数量选择 	-->
                  <u-number-box v-model="item.number" :min="1" :max="item.stock" integer
                    @change="(v) => handleQuantityChange(index, v)" />
                </view>
              </view>
            </view>
            <!-- 删除按钮 -->
            <view class="del flex-cen-ali position-absolute top-0 right-0" @click.stop="deleteItem(item)">
              <u-icon name="trash" size="36rpx" color="#830102"></u-icon>
            </view>
            <view v-if="item.add_type == 2" class="m-t-20 p-t-14 flex-ali-bet" style="border-top: 2rpx solid #E5E5E5;">
              <view class="font-26">
                材料小计
              </view>
              <view class="text-main font-32 font-weight-bold">￥{{ item.price / 100 }}</view>
            </view>
          </view>
        </view>
      </view>
    </u-checkbox-group>
    <specificationDetails ref="specificas"></specificationDetails>
    <template #bottom v-if="dataList.length > 0">
      <!-- 底部工具栏 -->
      <view class="flex-bet main-bg-color p-x-32 p-y-40">
        <view class="flex-ali">
          <u-checkbox :checked="allChecked" @change="toggleAll" activeColor="#830102">全选</u-checkbox>
          <text class="font-28 text-greey font-weight-middle">全选</text>
        </view>
        <view class="flex-ali m-l-30 flex-1">
          <view class="font-28 text-greey font-weight-middle">合计：</view>
          <view class="text-main font-38 font-weight-bold">¥{{ totalAmount.toFixed(2) }}</view>
        </view>
        <dy-button width="253rpx" btn_bg="#830102" @click="checkout">立即结算</dy-button>
      </view>
    </template>
  </z-paging>
</template>

<script setup>
import { myCartList, createOrder, delCart } from '@/api/api';
import { ref, computed } from 'vue';
import { onReachBottom, onShow, onReady, onLoad } from '@dcloudio/uni-app';
import { ShopCenterApi } from '../../api/serves';
const paging = ref(null);
const dataList = ref([]);
const checkboxValue = ref([]);
const specificas = ref(null);
import { useCounter } from '@/mixins/userHooks';
const { getUserInfo, userInfo, isLogin, tool } = useCounter();
import route from '@/uni_modules/uv-ui-tools/libs/util/route.js';

const queryList = async (pageNo, pageSize) => {
  // let { code, data, msg } = await ShopCenterApi.myCartList()
  // const list = [
  //   {
  //     name: '糖果红亚克力珠',
  //     image: 'https://cdn.example.com/product1.jpg',
  //     price: 168,
  //     quantity: 1,
  //     checked: false
  //   },
  //   {
  //     name: '星空蓝水晶珠',
  //     image: 'https://cdn.example.com/product2.jpg',
  //     price: 228,
  //     quantity: 2,
  //     checked: false
  //   }
  // ];
  myCartList().then((res) => {
    res.data.data.forEach((item) => {
      item.checked = false;
    });
    paging.value.complete(res.data.data);
  });
};

// 计算选中总金额
const totalAmount = computed(() => {
  return dataList.value.reduce((sum, item) => {
    return item.checked ? sum + (item.price / 100) * item.number : sum;
  }, 0);
});

// 计算全选状态
const allChecked = computed(() => {
  return (
    dataList.value.length > 0 && dataList.value.every((item) => item.checked)
  );
});

// 计算选中数量
const selectedCount = computed(() => {
  return dataList.value.filter((item) => item.checked).length;
});

// 单个商品选中状态变化
const handleCheckChange = (index, value) => {
  dataList.value[index].checked = value;
};

// 全选/反选
const toggleAll = (value) => {
  dataList.value.forEach((item) => (item.checked = value));
};

// 数量变化
const handleQuantityChange = (index, value) => {
  dataList.value[index].number = value;
};

// 删除商品
const deleteItem = (e) => {
  uni.showModal({
    title: '删除提示',
    content: '确定要删除该商品吗？',
    success: (res) => {
      if (res.confirm) {
        // dataList.value.splice(index, 1);
        delCart({ cart_id: [e.cart_id] }).then((res) => {
          if (res.code == 1) {
            paging.value.reload();
            uni.showToast({ title: '删除成功', icon: 'success' });
          } else {
            uni.showToast({ title: res.msg, icon: 'none' });
          }
        });
      }
    },
  });
};

// 去结算
const checkout = () => {
  if (selectedCount.value === 0) {
    uni.showToast({ title: '请选择要结算的商品', icon: 'none' });
    return;
  }
  let shopList = dataList.value.filter((item) => item.checked);
  console.log(shopList, '需要结算的商品');
  // uni.navigateTo({ url: '/packageOrder/orderConfirm/orderConfirm?shopList=' + JSON.stringify(shopList) });
  // 下单页面
  route({
    url: 'pagesA/pages/productList/orderConfirmation',
    params: {
      buy_mode: 2,
      shopList: encodeURIComponent(JSON.stringify(shopList)), //整个商品数据
    },
  });
};
onShow(() => {
  setTimeout(() => {
    paging.value.reload();
  }, 10);
});
</script>
<style>
page {
  background-color: #f8f8f8;
}
</style>
<style lang="scss" scoped>
::v-deep .u-number-box__plus {
  background: transparent !important;
}

::v-deep .u-number-box__minus {
  background: transparent !important;
}

::v-deep .u-number-box__input {
  width: 78rpx !important;
  height: 40rpx !important;
  border-radius: 12rpx !important;
}

::v-deep .uicon-plus {
  font-size: 24rpx !important;
}

::v-deep .uicon-minus {
  font-size: 24rpx !important;
}


.del {
  width: 60rpx;
  height: 60rpx;
  flex-shrink: 0;
  background: #ffe9ea;
  border-radius: 0 12rpx 0 12rpx !important;
}
</style>
